package com.deelete.springcloud.service.impl;

import com.deelete.springcloud.mapper.OrderMapper;
import com.deelete.springcloud.pojo.Order;
import com.deelete.springcloud.service.AccountService;
import com.deelete.springcloud.service.OrderService;
import com.deelete.springcloud.service.StorageService;
import com.deelete.springcloud.utils.CommonResult;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 订单服务实现类
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {


    @Autowired //订单Mapper
    private OrderMapper orderMapper;

    @Autowired //账户mapper
    private AccountService accountService;

    @Autowired //库存mapper
    private StorageService storageService;

    /**
     * 添加订单方法
     * @param order 订单
     * @return
     */
    @Override
    public Boolean addOrder(Order order) {
        return orderMapper.addOrder(order)>0;
    }

    @Override
    @GlobalTransactional
    public CommonResult<Order> createOrder(Order order) {
        //来一个id
        String sid = System.currentTimeMillis()+"";
        Long id = Long.parseLong(sid.substring(2,13));
        order.setId(id);
        CommonResult<Order> result = new CommonResult<>();
        log.info("开始插入订单");
        //判断下订单是否成功
        if(orderMapper.addOrder(order)>0){
            log.info("插入订单成功");

            log.info("开始减少库存");
            storageService.createStorage(order.getProductId(),order.getCount());
            log.info("结束减少库存");

            log.info("开始扣余额");
            accountService.CutAccount(order.getUserId(),order.getMoney());
            log.info("结束扣余额");

            log.info("开始更新订单状态");
            orderMapper.updateStatus(id);
            log.info("结束更新订单状态");

            result.setStatus(CommonResult.STATUS_SUCCESS);
            result.setMessage("下订单成功");
            result.setData(order);
        }else{
           result.setStatus(CommonResult.STATUS_ERROR);
           result.setMessage("插入订单失败");
        }
        return result;
    }
}
